<?php

namespace app\system\controller\daily;

use app\admin\controller\order\Throwable;
use app\common\controller\Backend;
use think\facade\Db;

/**
 * 订单列管理
 */
class Order extends Backend {
    /**
     * Order模型对象
     * @var object
     * @phpstan-var \app\admin\model\order\Order
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['out_trade_no', 'user.username'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\daily\Order;
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);

        $param = $this->request->param();

        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items();

        foreach ($list as $val) {
            $val->money = number_format($val->money);
            $val->create_time = date('Y-m-d H:i:s', $val->create_time);
        }

        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 确认订单
     */
    public function confirmOrder(): void {
        $param = $this->request->param();
        $update = [
            'status' => 1,
            'update_time' => $this->timestamp
        ];
        $result = Db::name('order')->where(['id' => $param['order_id']])->update($update);
        if ($result) {
            $this->success();
        } else {
            $this->error();
        }
    }

    /**
     * 取消订单
     */
    public function cancelOrder(): void {
        $param = $this->request->param();
        $where = [
            ['order_id', '=', $param['order_id']],
            ['status', '<>', 0]
        ];
        $order_goods = Db::name('order_goods')->where($where)->find();
        if ($order_goods) $this->error('该订单正在处理中，无法取消');
        $update = [
            'status' => 0,
            'update_time' => $this->timestamp
        ];
        $result = Db::name('order')->where(['id' => $param['order_id']])->update($update);
        if ($result) {
            $this->success();
        } else {
            $this->error();
        }
    }


    public function edit(): void {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (!$param) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $param = $this->excludeFields($param);

            $anchor_name = empty($param['anchor_name']) ? null : trim($param['anchor_name']);
            $live_time = empty($param['live_time']) ? null : trim($param['live_time']);
            $live_time = empty($live_time) ? null : strtotime($live_time);

            $data = [
                'anchor_name' => $anchor_name,
                'live_time' => $live_time
            ];

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($param);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row['live_time'] = empty($row['live_time']) ? '' : date('Y-m-d H:i:s', $row['live_time']);
        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}